package kcg;

import robocode.HitRobotEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import java.awt.Color;

/**
 * MikeTerry by Kelvin Green: Based on Wall sample Robot Walls - a sample robot by Mathew Nelson,
 * and maintained by Flemming N. Larsen.
 * <p/>
 * Moves around the outer edge with the gun facing in. Fires level 3 shots when energy is less then
 * enemy energy-15.0.
 * 
 * @version 1.1
 * @author Kelvin Green
 */
public class MikeTerry extends Robot {

  boolean peek; // Don't turn if there's a robot there.
  double moveAmount; // How much to move.
  boolean losing = false; // True if losing.

  /**
   * . run: Move around the walls.
   */
  public void run() {
    // Set colors.
    setBodyColor(Color.white);
    setGunColor(Color.green);
    setRadarColor(Color.green);
    setBulletColor(Color.green);
    setScanColor(Color.green);

    // Initialize moveAmount to the maximum possible for this battlefield.
    moveAmount = Math.max(getBattleFieldWidth(), getBattleFieldHeight());
    // Initialize peek to false.
    peek = false;

    // turnLeft to face a wall.
    // getHeading() % 90 means the remainder of.
    // getHeading() divided by 90.
    turnLeft(getHeading() % 90);
    ahead(moveAmount);
    // Turn the gun to turn right 90 degrees.
    peek = true;
    turnGunRight(90);
    turnRight(90);

    while (true) {
      // Look before we turn when ahead() completes.
      peek = true;
      // Move up the wall.
      ahead(moveAmount);
      // Don't look now
      peek = false;
      // Turn to the next wall.
      turnRight(90);
    }
  }

  /**
   * onHitRobot: Move away a bit.
   * 
   * @param e contains information about the enemy robot, e.g. its location.
   */
  public void onHitRobot(HitRobotEvent e) {
    // If he's in front of us, set back up a bit.
    if (e.getBearing() > -90 && e.getBearing() < 90) {
      back(100);
    } // else he's in back of us, so set ahead a bit.
    else {
      ahead(100);
    }
  }

  /**
   * onScannedRobot: Fire based on enemy distance unless losing.
   * 
   * @param e contains information about the enemy robot, e.g. its location.
   */
  public void onScannedRobot(ScannedRobotEvent e) {
    if ((e.getEnergy() - 15.0d) > this.getEnergy()) {
      losing = true;
    }
    if ((e.getEnergy() - 15.0d) < this.getEnergy()) {
      losing = false;
    }

    if (losing) {
      this.fire(3);
    }
    else {
      this.fire(Math.min(400 / e.getDistance(), 3));
    }
    // Note that scan is called automatically when the robot is moving.
    // By calling it manually here, we make sure we generate another scan event if there's a robot
    // on the next wall, so that we do not start moving up it until it's gone.
    if (peek) {
      scan();
    }
  }
}
